#!/usr/bin/env python
# -------
# Imports:
# -------
import os, logging, sys, pickle
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import users
from django.utils import simplejson
from settings import *
from core.models import *
from datetime import datetime

# ------------------------------------
class ThinImage(webapp.RequestHandler):
# ------------------------------------
    # -------------------------
    def parseFormVal(self, val):
    # -------------------------
        val = val.lower()
        if val == 'inf' or val == 'infinity':
            val = float(sys.maxint)
        return float(val)

    # ------------
    def post(self):
    # ------------
        # Pull out the paramaters
        ccId = int(self.request.get('ccId'))
        #relMin = self.parseFormVal(self.request.get('rel_min'))
        relMax = self.parseFormVal(self.request.get('rel_max'))
        #absMin = self.parseFormVal(self.request.get('abs_min'))
        absMax = self.parseFormVal(self.request.get('abs_max'))
        #thresholds = [(relMin, relMax),(absMin, absMax)]
        thresholds = (relMax, absMax)

        # Get the cell complex 
        cc = CellComplex.get_by_id(ccId)

        # Perform thinning 
        ccp = cc.load()
        R, I = cc.thin(ccp, thresholds)

        # Calculate the max of the thinned indices and replace the None's with the max iteration
        maxIndex = max([max(r) for r in R]) 
        R = [[v if v is not None else 100 for v in r] for r in R]

        # Store the thinning indices in the datastore
        tcp = ThinnedCellComplex()
        tcp.source = cc
        tcp.R = db.Blob(pickle.dumps(R))
        tcp.I = db.Blob(pickle.dumps(R))
        tcp.max_it = maxIndex
        tcp.put()
  
        toWrite = simplejson.dumps([tcp.key().id(), maxIndex])
        self.response.out.write(toWrite)
